
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import javax.swing.*;


class ReceivingThread extends Thread 
   {
	   public Socket sock;
	   private MDUser mdUser;
	   public File uploadFile=null;
	   public File downloadFile=null;
	   public File shareToolFile = null;
	   public File shareObjectFile = null;
	   
	   public ReceivingThread(MDUser mdUser, Socket sock){
		   this.mdUser = mdUser;
		   this.sock = sock;
	   }
	   
	   public void getShapeObjects(){
		   try {
			   ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
			   mdUser.ShapeObjects = (LinkedList<ShapeObject>)ois.readObject();
			   mdUser.md.refreshShapeObjects();
		   } catch (IOException e) {
			   e.printStackTrace();
		   } catch (ClassNotFoundException e) {
			   e.printStackTrace();
		   }
	   }
       public synchronized void run() 
       {
           Scanner remoteIn = null;
           try 
           {  
        	 getShapeObjects();
        	 remoteIn = new Scanner(sock.getInputStream());
             while (remoteIn.hasNextLine()){
                 String s = remoteIn.nextLine();
                 if(s.contains("<<OWNR>>")){
            		 String newControlOwner = s.split(" ")[2];
            		 System.out.println("got the list..yahoo");
            		 mdUser.usernameBox.setSelectedItem(newControlOwner);
            		 System.out.println("We are here");
            		 //set the current owner of control
            		 mdUser.md.ownerOfControl = newControlOwner;
            		 
            		 // ensure owner received
            		 mdUser.ownerreceived = true;
            		 while(true)
            		 {
            			 System.out.println("OWNER received first");
            			if(mdUser.md.toolbarintialized != false)
            				break;
            		 }
            		 
            		 
            		 if(mdUser.md.userName.equals(newControlOwner))
            		 {
            			 mdUser.serverText.append("MDServer: You are now the owner of control" + "\n");
            			 System.out.println("Enabling behavior..");
            			 mdUser.md.changeToolBehavior(true);
            		 }
            		 else
            		 {
            			 mdUser.serverText.append("MDServer: " + newControlOwner + " is the new owner of control" + "\n");
            			 mdUser.md.changeToolBehavior(false);
            		 }
                	 mdUser.serverText.setCaretPosition(mdUser.serverText.getText().length()-1);
            	 }else if(s.contains("<<USRLFT>>")){
            		 mdUser.usernameBox.removeItem(s.split(" ")[2]);
            		 mdUser.serverText.append("MDServer: " + s.split(" ")[2] + " has left the dicussion.\n");
            		 mdUser.serverText.setCaretPosition(mdUser.serverText.getText().length()-1);
            	 }
            	 else if(s.contains("<<REFSHAPEOBJS>>")){
                	 if(s.contains("<<LAST>>")){
                		 mdUser.remoteOut.println("<<REFALLREADY>>");
                	 }
                	 getShapeObjects();
                	 mdUser.md.canvas.getCurrentTool().paintObjects(1);
                 }else if(s.contains("<<READY>>")){
                	 mdUser.sendShapeObjects();
                 }else if(s.contains("<<GOTEM>>")){
                	 mdUser.remoteOut.println("<<REF>>");
                 }else if(s.contains("<<USRMSG>>")){
                	 mdUser.serverText.append(s.replace("<<USRMSG>>","") + "\n");
                	 mdUser.serverText.setCaretPosition(mdUser.serverText.getText().length()-1);
                 }else if(s.contains("<<RETURNFILENAME>>")){
                	 mdUser.setFileName(s.replace("<<RETURNFILENAME>>",""));
                 }else if(s.contains("<<USRLST>>")){
                	 System.out.println("Here");
                	 if(!mdUser.loadCurrentUsers(s))
                	 {
                		 System.out.println("Requesting for user list again");
                		 mdUser.remoteOut.println("<<BRDCSTUSRLST>>");
                	 }
                 }else if(s.contains("<<DOWNLOADFILE>>")){
                	 File dir = new File ("Drawings/");
          	         String[] filenames = dir.list();
          	         String fileName = s.replace("<<DOWNLOADFILE>>","");
          	         String fn = fileName.replace("Drawings/","");
          	         boolean duplicate = false;
          	         for(String str: filenames){
          	        	if (str.equals(fn)){
          	        		duplicate = true;
          	        	}
          	         }
          	         if(duplicate){
          	        	 JOptionPane.showMessageDialog(null, "This file already exists in your \"Drawings\" folder. \n"+
          	        			 "Please rename your drawing or save the drawing you wish to download with a different name.");
          	         }
          	        if(!duplicate){
          	        	mdUser.remoteOut.println("<<READYTODOWNLOADFILE>>"+
          	        			s.replace("<<DOWNLOADFILE>>",""));
          	        	ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
          	        	try {
          	        		File file = (File)ois.readObject();
						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						} 
          	        }
                 }else if (s.contains("<<READYFORUPLOAD>>")){
                	 if(uploadFile != null){
	         			ObjectOutputStream oos;
	         			try {	         				
	         				oos = new ObjectOutputStream(sock.getOutputStream());
	         				oos.writeObject(uploadFile);
	         			} catch (IOException ioe) {
	         				ioe.printStackTrace();
	         			}
                	 }
             	}else if (s.contains("<<SENDINGCLASSFILE>>")){
             		//get ready to receive a file
             		ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
      	        	try {
      	        		File classfile = (File)ois.readObject();
      	        		System.out.println(classfile.getName());
					} catch (ClassNotFoundException e) {e.printStackTrace();}
             	}else if(s.contains("<<DUPLICATE>>")){
             		System.out.println(s);
             		JOptionPane.showMessageDialog(null, "The file you are trying to upload \""+
             				s.replace("<<DUPLICATE>>", "")+
             				"\" already exists. \n"+
             				"Please rename your file and upload again.");
                }else if(s.contains("<<FILENAME>>")){
                	 String str = s.subSequence(s.lastIndexOf(" ")+13, s.length()).toString();
                	 if((mdUser.md.open0_delete1_download2_toggle == 0 && mdUser.md.openMenu.getItemCount()==0) ||
                			 (mdUser.md.open0_delete1_download2_toggle == 1 && mdUser.md.deleteMenu.getItemCount()==0) ||
                			 (mdUser.md.open0_delete1_download2_toggle == 2 && mdUser.md.downloadMenu.getItemCount()==0)){
                		 mdUser.md.open_delete_download_Frame = new JFrame();
                		 mdUser.md.open_delete_download_Frame.setLocation(50, 50);
                		 mdUser.md.open_delete_download_Frame.setLayout(new BorderLayout());
                		 mdUser.md.open_delete_download_Frame.setSize(200, 100);
                		 mdUser.md.open_delete_download_Frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                		 if(mdUser.md.open0_delete1_download2_toggle == 0){
                			 mdUser.md.open_delete_download_Frame.setTitle("Open");
                		 }else if(mdUser.md.open0_delete1_download2_toggle == 1){
                			 mdUser.md.open_delete_download_Frame.setTitle("Delete");
                		 }else if(mdUser.md.open0_delete1_download2_toggle == 2){
                			 mdUser.md.open_delete_download_Frame.setTitle("Download");
                		 }
                		 mdUser.md.open_delete_download_Box = new JComboBox();                		
                		 mdUser.md.open_delete_download_Frame.add(mdUser.md.open_delete_download_Box, BorderLayout.NORTH);
                		 JPanel buttonPanel = new JPanel(new GridLayout(1,2));
                		 JButton op_del_button = new JButton();
                		 if(mdUser.md.open0_delete1_download2_toggle == 0){
                			 op_del_button.setText("Open");
                			 op_del_button.addActionListener(new DrawingMenuItemListener(mdUser.md,"openButton"));
                		 }else if(mdUser.md.open0_delete1_download2_toggle == 1){
                			 op_del_button.setText("Delete");
                			 op_del_button.addActionListener(new DrawingMenuItemListener(mdUser.md,"deleteButton"));
                		 }else if(mdUser.md.open0_delete1_download2_toggle == 2){
                			 op_del_button.setText("Download");
                			 op_del_button.addActionListener(new DrawingMenuItemListener(mdUser.md,"downloadButton"));
                		 }
                		 JButton cancel = new JButton("Cancel");
                		 cancel.addActionListener(new DrawingMenuItemListener(mdUser.md,"cancelButton"));
                		 buttonPanel.add(op_del_button);
                		 buttonPanel.add(cancel);
                		 mdUser.md.open_delete_download_Frame.add(buttonPanel, BorderLayout.SOUTH);
                		 mdUser.md.open_delete_download_Frame.setVisible(false);
                		 JMenuItem show = new JMenuItem("<Show All>");
                		 show.addActionListener(new DrawingMenuItemListener(mdUser.md,"<Show All>"));
                		 mdUser.md.open_delete_download_Box.addItem(str);
                		 if(mdUser.md.open0_delete1_download2_toggle == 0){
                			 mdUser.md.openMenu.add(show);
                		 }else if(mdUser.md.open0_delete1_download2_toggle == 2){
                			 mdUser.md.downloadMenu.add(show);
                		 }
                		 JMenuItem jmi = new JMenuItem(str);
	                	 jmi.addActionListener(new DrawingMenuItemListener(mdUser.md,str));
	                	 if(mdUser.md.open0_delete1_download2_toggle == 0){
	                		 mdUser.md.openMenu.add(jmi);
	                	 }else if(mdUser.md.open0_delete1_download2_toggle == 1){
	                		 mdUser.md.deleteMenu.add(jmi);
	                	 }else if(mdUser.md.open0_delete1_download2_toggle == 2){
	                		 mdUser.md.downloadMenu.add(jmi);
	                	 }
                	 }else if(mdUser.md.open0_delete1_download2_toggle == 0){ 
                		 if(mdUser.md.openMenu.getItemCount()<=10){
		                	 JMenuItem jmi = new JMenuItem(str);
		                	 jmi.addActionListener(new DrawingMenuItemListener(mdUser.md,str));
		                	 mdUser.md.openMenu.add(jmi);
                		 }
                		 mdUser.md.open_delete_download_Box.addItem(str);
                	 }else if(mdUser.md.open0_delete1_download2_toggle == 1){
                		 if(mdUser.md.deleteMenu.getItemCount()<=10){
		                	 JMenuItem jmi = new JMenuItem(str);
		                	 jmi.addActionListener(new DrawingMenuItemListener(mdUser.md,str));
		                	 mdUser.md.deleteMenu.add(jmi);
                		 }
                		 mdUser.md.open_delete_download_Box.addItem(str);
                	 }else if(mdUser.md.open0_delete1_download2_toggle == 2){
                		 if(mdUser.md.deleteMenu.getItemCount()<=10){
		                	 JMenuItem jmi = new JMenuItem(str);
		                	 jmi.addActionListener(new DrawingMenuItemListener(mdUser.md,str));
		                	 mdUser.md.downloadMenu.add(jmi);
                		 }
                		 mdUser.md.open_delete_download_Box.addItem(str);
                	 }
                 }else if(s.contains("<<TESTTOOL>>")){
                	 System.out.println();
                	 try {
                		 System.out.println("tool add begin");
             			Class c = Class.forName("RectangleTool");
             			Class[] constrArgsClass = new Class[]{DrawingCanvas.class, LinkedList.class, MDUser.class};
             			Object[] constrArgs = new Object[]{mdUser.md.canvas, mdUser.md.ShapeObjects, mdUser};
             			Constructor constr = c.getConstructor(constrArgsClass);
             			Object o = constr.newInstance(constrArgs);
             			ToolListener tl = new ToolListener("Rectangle",
             					mdUser.md.getImageIcon("rectangle.jpg"),
             					"Rectangle drawing tool",
             					mdUser.md.canvas,
             			(Tool)o);
             			mdUser.md.toolList.add(tl);
             			mdUser.md.toolBar.addItem(tl);
             			mdUser.md.menuBar.addTool(tl);
             			mdUser.md.validate();
             			System.out.println("tool add done");
	             		} catch (ClassNotFoundException e) {e.printStackTrace();} 
	             		catch (InstantiationException e) {e.printStackTrace();}
	             		catch (IllegalAccessException e) {e.printStackTrace();}
	             		catch (SecurityException e) {e.printStackTrace();} 
	             		catch (NoSuchMethodException e) {e.printStackTrace();}
	             		catch (IllegalArgumentException e) {e.printStackTrace();}
	             		catch (InvocationTargetException e) {e.printStackTrace();} 
                 }
             }
           }
           catch (IOException e){ 
        	   System.out.println(e.getMessage() + ": Connection to peer lost."); 
           } 
           finally 
           {  
              if (remoteIn != null) remoteIn.close(); 
           }
       }
 
   }